package com.atguigu.gulimall.order.listener;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 订单监听类
 *
 * @author xiaoping
 * @create 2020/7/8 16:24
 * @since 1.0.0
 */
@RabbitListener(queues = {"order.release.order.queue"})
@Service
public class OrderCloseListener {

    @Autowired
    OrderService orderService;

    /**
     * 监听order.release.order.queue队列消息
     * 以便于创建队列，交换机，绑定关系
     * @param entity
     */
    @RabbitHandler
    public void listener(OrderEntity entity, Channel channel, Message message) throws IOException {
        System.out.println("收到过期的订单信息：准备关闭订单" + entity.getOrderSn());
        try {
            orderService.closeOrder(entity);
            //手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            //拒绝消息，并重新放入到队列中让确认人消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
